var versewise = angular.module('versewise', ['monospaced.mousewheel']);

versewise.controller('VersewiseCtrl', ['$scope', VersewiseCtrl]);

versewise.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

function VersewiseCtrl($scope) {

    $scope.allSurahs = allSurahs;
    $scope.verses = [];

    $scope.viewStart = 0;

    $scope.jumpToText = "";

    $scope.favourites = [];

    $scope.recent = [];

    $scope.history = [];
    $scope.historyCurrent = -1;

    $scope.logHistory = true;

    $scope.addToFavourite = function() {
        var val = $scope.currentPreview.name + ":" + $scope.currentPreview.verse;
        var index = $scope.favourites.indexOf(val);
        if(index == -1) {
            $scope.favourites.push(val);
            $("#favouriteIcon").removeClass("glyphicon-heart-empty").addClass("glyphicon-heart");
        } else {
            $scope.favourites.splice(index, 1);
            $("#favouriteIcon").removeClass("glyphicon-heart").addClass("glyphicon-heart-empty");
        }
    }

    $scope.gotoFavourite = function(val) {
        $scope.jumpToText = $scope.favourites[val];
        $scope.logHistory = false;
        $scope.jumpTo();
        $scope.logHistory = true;
    }


    $scope.gotoRecent = function(val) {
        $scope.jumpToText = $scope.recent[val];
        $scope.logHistory = false;
        $scope.jumpTo();
        $scope.logHistory = true;
    }

    $scope.historyBack = function() {
        if($scope.historyCurrent > 0) {
            $scope.gotoHistory($scope.historyCurrent - 1);
        }
    }

    $scope.historyNext = function() {
        if($scope.historyCurrent < $scope.history.length - 1) {
            $scope.gotoHistory($scope.historyCurrent + 1);
        }
    }

    $scope.historyClass = function(index) {
        return index == $scope.historyCurrent ? "active" : "";
    };

    $scope.logHistoryValue = function() {
        var addToHistory = function() {
            $scope.historyCurrent++;
            $scope.history = $scope.history.slice(0, $scope.historyCurrent);
            $scope.history.push($scope.jumpToText);

            if($scope.history.length > 2000) {
                $scope.history = $scope.history.slice(1, 2000);
                $scope.historyCurrent = 1999;
            }

            if($scope.recent.indexOf($scope.jumpToText) == -1) {
                $scope.recent.push($scope.jumpToText);
            }
        }
        if($scope.logHistory ) {
            if($scope.history.length == 0) {
                addToHistory();
            } else {
                if($scope.history[$scope.history.length - 1] != $scope.jumpToText) {
                    addToHistory();
                }
            }
        }
    };


    $scope.gotoHistory = function(val) {
        $scope.jumpToText = $scope.history[val];
        $scope.historyCurrent = val;
        $scope.logHistory = false;
        $scope.jumpTo();
        $scope.logHistory = true;
    };

    $scope.versesView = function () {
        return $scope.verses.slice($scope.viewStart, $scope.viewStart + 20);
    };

    $scope.newTag = {
        surah: allSurahs[0].name,
        verse: 1
    };

    $scope.showAddTag = function (verse) {
        $scope.secleted = verse;
        $("#addTag").modal();
    };

    $scope.addTag = function () {

        var verseValid = $scope.newTag.verse > 0;
        if (verseValid) {
            angular.forEach($scope.allSurahs, function (surah) {
                if (surah.name == $scope.newTag.surah) {
                    verseValid = surah.verses >= $scope.newTag.verse;
                    if (verseValid) {
                        angular.forEach($scope.secleted.tags, function (tag) {
                            if (tag.name == $scope.newTag.surah && tag.verse == $scope.newTag.verse) {
                                verseValid = false;

                                return false;
                            }
                        });
                    }
                    return false;
                }
            });
        }

        if (verseValid) {
            $scope.secleted.tags.push({
                name: $scope.newTag.surah,
                verse: $scope.newTag.verse,
                comments: $scope.newTag.comments
            });
            $("#addTagAlert").hide('slow');
        } else {
            $("#addTagAlert").show('slow');
        }
    };

    $scope.secleted = {};

    $scope.outputData = function () {
        return 123;//return JSON.stringify($scope.verses, censor, 2);
    };

    $scope.gotoTag = function (tag) {
//        var num = surahNumber(tag.name);
//        var total = 0;
//        for (var i = 0; i < num - 1; i++) {
//            total += allSurahs[i].verses;
//        }
//        total += tag.verse - 1;
//        $scope.setStartValue(total);
        var num = surahNumber(tag.name);
        $scope.jumpToText = num + ":" + tag.verse;
        $scope.jumpTo();

    };

    $scope.setStartValue = function (val) {
        $scope.viewStart = (val + 20 > $scope.verses.length ) ? $scope.verses.length - 20 : val;

    };

    $scope.scrollVerses = function (event, delta, deltaX, deltaY) {
        if ($scope.viewStart - deltaY < 0) {
            return;
        }
        $scope.setStartValue($scope.viewStart - deltaY);
    };

    $scope.firstPage = function () {
        $scope.setStartValue(0);
    };

    $scope.lastPage = function () {
        $scope.setStartValue($scope.verses.length);
    };

    $scope.nextPage = function () {
        if ($scope.viewStart + 20 > $scope.verses.length) {
            return;
        }
        $scope.setStartValue($scope.viewStart + 20);
    };

    $scope.prevPage = function () {
        if ($scope.viewStart - 20 < 0) {
            return;
        }
        $scope.setStartValue($scope.viewStart - 20);
    };

    $scope.jumpTo = function () {
        $("#search").removeClass("has-error");
        $("#search").removeClass("has-success");

        try {
            var vals = $scope.jumpToText.split(":");


            var num = parseInt(vals[0]);
            if(isNaN(num)) {
                num = surahNumber(vals[0]);
            }

            if (num < 1 || num > allSurahs.length) {
                $("#search").addClass("has-error");
                return;
            }

            var total = 0;
            for (var i = 0; i < num - 1; i++) {
                total += allSurahs[i].verses;
            }
            var verse = parseInt(vals[1]);
            if (verse < 1 || verse > allSurahs[num - 1].verses) {
                $("#search").addClass("has-error");
                return;
            }
            total += verse - 1;
            $scope.setStartValue(total);
            $scope.logHistoryValue();

            $("#search").addClass("has-success");
        } catch (e) {
            $("#search").addClass("has-error");
        }
    };

    $scope.isInFavourites = function(verse) {
        return $scope.favourites.indexOf(verse.name + ":" + verse.verse) > -1;
    }

    $scope.showPreview = function(verse, comment) {
        $scope.currentPreview = verse;
        $("#previewArea").show();
        $("#preview").attr("src", "http://www.alislam.org/quran/search2/verses/" + pad(surahNumber(verse.name)) + "-" + pad(verse.verse) + ".png");
        $("#pagePreview").attr("href", "http://www.alislam.org/quran/search2/showChapter.php?ch=" + surahNumber(verse.name) + "&verse=" + verse.verse);
        $("#pagePreview").text(verse.name + ":" + verse.verse);
        $("#commentsPreview").html(comment);
        if($scope.isInFavourites(verse)) {
            $("#favouriteIcon").removeClass("glyphicon-heart-empty").addClass("glyphicon-heart");
        } else {
            $("#favouriteIcon").removeClass("glyphicon-heart").addClass("glyphicon-heart-empty");
        }
    }

    $scope.showAyah = function(verse) {
        $scope.showPreview(verse, "");
    };

    $scope.showTag = function(tag) {
        $scope.showPreview(tag, tag.comments);
    };


    /********************** constructor ********************/
    fillData($scope.verses);

}

function censor(key, value) {
    if (key.indexOf("$$") == 0) {
        return undefined;
    }
    return value;
}

var allSurahs = [
    {name: "Al-Fatiha", verses: 6 + 1},
    {name: "Al-Baqara", verses: 286 + 1},
    {name: "Al Imran", verses: 200 + 1},
    {name: "An-Nisa", verses: 176 + 1},
    {name: "Al-Maida", verses: 120 + 1},
    {name: "Al-Anam", verses: 165 + 1},
    {name: "Al-Araf", verses: 206 + 1},
    {name: "Al-Anfal", verses: 75 + 1},
    {name: "At-Tawba", verses: 128 + 1},
    {name: "Yunus", verses: 109 + 1},
    {name: "Hud", verses: 123 + 1},
    {name: "Yusuf", verses: 111 + 1},
    {name: "Ar-Rad", verses: 43 + 1},
    {name: "Ibrahim", verses: 52 + 1},
    {name: "Al-Hijr", verses: 99 + 1},
    {name: "An-Nahl", verses: 128 + 1},
    {name: "Al-Isra", verses: 111 + 1},
    {name: "Al-Kahf", verses: 110 + 1},
    {name: "Maryam", verses: 98 + 1},
    {name: "Ta-Ha", verses: 135 + 1},
    {name: "Al-Anbiya", verses: 112 + 1},
    {name: "Al-Hajj", verses: 78 + 1},
    {name: "Al-Muminoon", verses: 118 + 1},
    {name: "An-Nur", verses: 64 + 1},
    {name: "Al-Furqan", verses: 77 + 1},
    {name: "Ash-Shuara", verses: 227 + 1},
    {name: "An-Naml", verses: 93 + 1},
    {name: "Al-Qasas", verses: 88 + 1},
    {name: "Al-Ankabut", verses: 69 + 1},
    {name: "Ar-Rum", verses: 60 + 1},
    {name: "Luqman", verses: 34 + 1},
    {name: "As-Sajda", verses: 30 + 1},
    {name: "Al-Ahzab", verses: 73 + 1},
    {name: "Saba", verses: 54 + 1},
    {name: "Fatir (Al-Malaikah)", verses: 45 + 1},
    {name: "Ya Sin", verses: 83 + 1},
    {name: "As-Saaffat", verses: 182 + 1},
    {name: "Sad", verses: 88 + 1},
    {name: "Az-Zumar", verses: 75 + 1},
    {name: "Ghafir", verses: 85 + 1},
    {name: "Fussilat", verses: 54 + 1},
    {name: "Ash-Shura", verses: 53 + 1},
    {name: "Az-Zukhruf", verses: 89 + 1},
    {name: "Ad-Dukhan", verses: 59 + 1},
    {name: "Al-Jathiya", verses: 37 + 1},
    {name: "Al-Ahqaf", verses: 35 + 1},
    {name: "Muhammad", verses: 38 + 1},
    {name: "Al-Fath", verses: 29 + 1},
    {name: "Al-Hujurat", verses: 18 + 1},
    {name: "Qaf", verses: 45 + 1},
    {name: "Adh-Dhariyat", verses: 60 + 1},
    {name: "At-Tur", verses: 49 + 1},
    {name: "An-Najm", verses: 62 + 1},
    {name: "Al-Qamar", verses: 55 + 1},
    {name: "Ar-Rahman", verses: 78 + 1},
    {name: "Al-Waqia", verses: 96 + 1},
    {name: "Al-Hadid", verses: 29 + 1},
    {name: "Al-Mujadila", verses: 22 + 1},
    {name: "Al-Hashr", verses: 24 + 1},
    {name: "Al-Mumtahina", verses: 13 + 1},
    {name: "As-Saff", verses: 14 + 1},
    {name: "Al-Jumua", verses: 11 + 1},
    {name: "Al-Munafiqun", verses: 11 + 1},
    {name: "At-Taghabun", verses: 18 + 1},
    {name: "At-Talaq", verses: 12 + 1},
    {name: "At-Tahrim", verses: 12 + 1},
    {name: "Al-Mulk", verses: 30 + 1},
    {name: "Al-Qalam", verses: 52 + 1},
    {name: "Al-Haaqqa", verses: 52 + 1},
    {name: "Al-Maarij", verses: 44 + 1},
    {name: "Nuh", verses: 28 + 1},
    {name: "Al-Jinn", verses: 28 + 1},
    {name: "Al-Muzzammil", verses: 20 + 1},
    {name: "Al-Muddathir", verses: 56 + 1},
    {name: "Al-Qiyama", verses: 40 + 1},
    {name: "Al-Insan (al-Dahr)", verses: 31 + 1},
    {name: "Al-Mursalat", verses: 50 + 1},
    {name: "An-Naba", verses: 40 + 1},
    {name: "An-Naziat", verses: 46 + 1},
    {name: "Abasa", verses: 42 + 1},
    {name: "At-Takwir", verses: 29 + 1},
    {name: "Al-Infitar", verses: 19 + 1},
    {name: "Al-Mutaffifin", verses: 36 + 1},
    {name: "Al-Inshiqaq", verses: 25 + 1},
    {name: "Al-Burooj", verses: 22 + 1},
    {name: "At-Tariq", verses: 17 + 1},
    {name: "Al-Ala", verses: 19 + 1},
    {name: "Al-Ghashiya", verses: 26 + 1},
    {name: "Al-Fajr", verses: 30 + 1},
    {name: "Al-Balad", verses: 20 + 1},
    {name: "Ash-Shams", verses: 15 + 1},
    {name: "Al-Lail", verses: 21 + 1},
    {name: "Ad-Dhuha", verses: 11 + 1},
    {name: "Al-Inshirah", verses: 8 + 1},
    {name: "At-Tin", verses: 8 + 1},
    {name: "Al-Alaq", verses: 19 + 1},
    {name: "Al-Qadr", verses: 5 + 1},
    {name: "Al-Bayyina", verses: 8 + 1},
    {name: "Az-Zalzala", verses: 8 + 1},
    {name: "Al-Adiyat", verses: 11 + 1},
    {name: "Al-Qaria", verses: 11 + 1},
    {name: "At-Takathur", verses: 8 + 1},
    {name: "Al-Asr", verses: 3 + 1},
    {name: "Al-Humaza", verses: 9 + 1},
    {name: "Al-Fil", verses: 5 + 1},
    {name: "Quraysh", verses: 4 + 1},
    {name: "Al-Maun", verses: 7 + 1},
    {name: "Al-Kawthar", verses: 3 + 1},
    {name: "Al-Kafirun", verses: 6 + 1},
    {name: "An-Nasr", verses: 3 + 1},
    {name: "Al-Masadd", verses: 5 + 1},
    {name: "Al-Ikhlas", verses: 4 + 1},
    {name: "Al-Falaq", verses: 5 + 1},
    {name: "Al-Nas", verses: 6 + 1}

];




function surahNumber(surah) {
    for (var i = 0; i < allSurahs.length; i++) {
        if (allSurahs[i].name == surah)
            return i + 1;
    }
}
function pad(num) {
    var s = "00" + num;
    return s.substr(s.length - 3);
}